﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Rizmar.RizmarDataSetTableAdapters;

namespace Rizmar
{
    public partial class Titulo : UserControl
    {
        LancamentoForm parent;
        private decimal pisTitulo;
        private decimal cofinsTitulo;
        private decimal issTitulo;
        private decimal iofTitulo;
        private decimal cpmfTitulo;
        private decimal taxaAdm, duplicata;
        internal int n_digitos;

        public void settaxaAdm(decimal txAdm)
        {
            taxaAdm = txAdm;
        }

        public decimal gettaxaAdm() 
        {
            return taxaAdm;
        }

        public void setDuplicata(decimal dup)
        {
            duplicata = dup;
        }

        public decimal getDuplicata() 
        {
            return duplicata;
        } 

        public void setPis(decimal pis)
        {
            pisTitulo = pis;
        }

        public void setCofins(decimal cofins)
        {
            cofinsTitulo = cofins;
            
        }

        public void setIss(decimal iss)
        {
            issTitulo = iss;
            
        }

        public void setIof(decimal iof)
        {
            iofTitulo = iof;
            
        }

        public void setCpmf(decimal cpmf)
        {
            cpmfTitulo = cpmf;
         
        }

        public decimal getPis() 
        {
            return pisTitulo;
        }

        public decimal getCofins()
        {
            return cofinsTitulo;
        }

        public decimal getIss()
        {
            return issTitulo;
        }

        public decimal getIof()
        {
            return iofTitulo;
        }

        public decimal getCpmf()
        {
            return cpmfTitulo;
        }

        public Titulo()
        {
            InitializeComponent();
        }

        public Titulo(LancamentoForm form)
        {
            parent = form;
            InitializeComponent();
        }

        public bool Completo()
        {
            if (codigoTextBox.Text == string.Empty )
                return false;
            if (chequeRadioButton.Checked)
              if (bancoTextBox.Text == string.Empty)
                return false;
            if (sacadoTextBox.Text == string.Empty)
                return false;
            if (valorTextBox.Text == string.Empty)
                return false;
            return true; ;
        }

        private void valorTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {           
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) && (e.KeyChar != '.' && e.KeyChar != ','))
                e.Handled = true;
            if ((e.KeyChar == '.' ) && ((parent.titulos[parent.n_titulos - 1].valorTextBox.Text.Contains(".")||(parent.titulos[parent.n_titulos - 1].valorTextBox.Text.Contains(",")))))
                e.Handled = true;
            if ((e.KeyChar == ',') && ((parent.titulos[parent.n_titulos - 1].valorTextBox.Text.Contains(",") || (parent.titulos[parent.n_titulos - 1].valorTextBox.Text.Contains(".")))))
                e.Handled = true;
            if ((parent.titulos[parent.n_titulos - 1].valorTextBox.Text.Contains(".")&& (parent.titulos[parent.n_titulos - 1].valorTextBox.Text.Length - parent.titulos[parent.n_titulos - 1].valorTextBox.Text.IndexOf('.') >= 3)) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            if ((parent.titulos[parent.n_titulos - 1].valorTextBox.Text.Contains(",") && (parent.titulos[parent.n_titulos - 1].valorTextBox.Text.Length - parent.titulos[parent.n_titulos - 1].valorTextBox.Text.IndexOf(',') >= 3)) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            if (e.KeyChar == '\r')
            {
                if (valorTextBox.Text != string.Empty)
                {
                    e.Handled = true;
                    parent.novoButton.Focus();
                    setDiasLabelText();
                    setLiquidoLabelText();
                    setDesagioLabelText();
                }

            }
        }

        private void dTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
        }

        private void valorTextBox_Enter(object sender, EventArgs e)
        {
            System.Windows.Forms.Clipboard.Clear();

        }

        private void bancoTextBox_Enter(object sender, EventArgs e)
        {
            System.Windows.Forms.Clipboard.Clear();
        }

        private void codigoTextBox_Enter(object sender, EventArgs e)
        {
            
            System.Windows.Forms.Clipboard.Clear();
        }

        private void desagioTextBox_Enter(object sender, EventArgs e)
        {
            System.Windows.Forms.Clipboard.Clear();
        }

        private void liquidoTextBox_Enter(object sender, EventArgs e)
        {
            System.Windows.Forms.Clipboard.Clear();
        }

        private void diasTextBox_Enter(object sender, EventArgs e)
        {
            System.Windows.Forms.Clipboard.Clear();
        }

        private void dTextBox_Enter(object sender, EventArgs e)
        {
            System.Windows.Forms.Clipboard.Clear();
        }

        private void pesquisaSacadoButton_Click(object sender, EventArgs e)
        {
                PesquisaSacadoForm form = new PesquisaSacadoForm(parent);
                form.ShowDialog();
        }

        private void tipoComboBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
        }

        private void bancoTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
        }

        private void codigoTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if ((parent as LancamentoForm).verificaCodigo())
                {
                    e.Handled = true;
                    System.Windows.Forms.SendKeys.Send("{TAB}");
                }
            }
        }

        private void sacadoTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
        }

        private void dataBaseDateTimePicker_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
            else
            {
                if (++n_digitos == 2 || n_digitos == 5)
                    System.Windows.Forms.SendKeys.Send("/");
                else if (n_digitos == 10)
                {
                    System.Windows.Forms.SendKeys.Send("{LEFT}");
                    System.Windows.Forms.SendKeys.Send("{LEFT}");
                    n_digitos = 0;
                }
            }
        }

        private void vencimentoDateTimePicker_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
            else
            {
                if (++n_digitos == 2 || n_digitos == 5)
                    System.Windows.Forms.SendKeys.Send("/");
                else if (n_digitos == 10)
                {
                    System.Windows.Forms.SendKeys.Send("{LEFT}");
                    System.Windows.Forms.SendKeys.Send("{LEFT}");
                    n_digitos = 0;
                }
            }
        }

        public void setDiasLabelText()
        {
            ClienteTableAdapter cta = new ClienteTableAdapter();
            RizmarDataSet.ClienteDataTable cdt = new RizmarDataSet.ClienteDataTable();

            int d;
            int dias;
            int dMais;
            cdt = cta.PesquisaPorID(Convert.ToInt32(parent.textBoxCódigo.Text));
            if (cdt.Rows.Count > 0)
            {
                d = Convert.ToInt32(cdt.Rows[0]["d"]);

                if (dTextBox.Text == string.Empty) 
                    dMais = 0;
                else
                    dMais = Convert.ToInt32(dTextBox.Text);

                DateTime SomaDias;
                SomaDias = vencimentoDateTimePicker.Value;
                
                if (SomaDias.DayOfWeek == DayOfWeek.Sunday)
                {
                    SomaDias = SomaDias.AddDays(1);
                }
                else
                    if (SomaDias.DayOfWeek == DayOfWeek.Saturday)
                    {
                        SomaDias = SomaDias.AddDays(2);
                    }else
                        if (SomaDias.DayOfWeek == DayOfWeek.Friday) 
                        {
                            SomaDias = SomaDias.AddDays(2);
                        }
                SomaDias = SomaDias.AddDays(d + dMais);
                TimeSpan diferenca = SomaDias.Subtract(dataBaseDateTimePicker.Value);
                dias = Convert.ToInt32(diferenca.Days);
                dias = dias + 2;
                diasValorLabel.Text = Convert.ToString(dias);
            }
        }

        public void setLiquidoLabelText()
        {
            ClienteTableAdapter cta = new ClienteTableAdapter();
            RizmarDataSet.ClienteDataTable cdt = new RizmarDataSet.ClienteDataTable();
            double taxaMensal = 0;
            double taxaADM = 0;
            //double duplicata = 0;
            cdt = cta.PesquisaPorID(Convert.ToInt32(parent.textBoxCódigo.Text));
            if (cdt.Rows.Count > 0)
            {
                string STtaxaMensal = Convert.ToString(cdt.Rows[0]["taxa"]).Replace('.', ',');
                string STtaxaADM = Convert.ToString(cdt.Rows[0]["adm"]).Replace('.', ',');
                string STduplicata = Convert.ToString(cdt.Rows[0]["duplicata"]).Replace('.', ',');
                taxaMensal = Convert.ToDouble(STtaxaMensal);
                taxaADM = Convert.ToDouble(STtaxaADM);
                setDuplicata(Convert.ToDecimal(STduplicata));
                //duplicata = Convert.ToDouble(STduplicata);
            }
           
            int dia = Convert.ToInt32(diasValorLabel.Text);
            double jurosDia = (((taxaMensal + taxaADM)* 0.01) / 30);
            double liq = 0;
            if (chequeRadioButton.Checked == true)
            {
                liq = double.Parse(valorTextBox.Text.Replace('.', ',')) - ((double.Parse(valorTextBox.Text.Replace('.', ',')) * (double)Math.Pow((1 + jurosDia), dia) - double.Parse(valorTextBox.Text.Replace('.', ','))));
            }
            else
                if (duplicataRadioButton.Checked == true)
                {
                    liq = double.Parse(valorTextBox.Text.Replace('.', ',')) - (((double.Parse(valorTextBox.Text.Replace('.', ',')) * (double)Math.Pow((1 + jurosDia), dia))) - double.Parse(valorTextBox.Text.Replace('.', ','))) - Convert.ToDouble(getDuplicata());                    
                }
            
            liquidoValorLabel.Text = Convert.ToString(decimal.Round(Convert.ToDecimal(liq), 2));
        }

        public void setDesagioLabelText()
        {
            float pis = 0, cofins = 0, cpmf = 0, iof = 0, iss = 0, adValore = 0;
            TaxaTableAdapter tta = new TaxaTableAdapter();
            RizmarDataSet.TaxaDataTable tdt = new RizmarDataSet.TaxaDataTable();

            tdt = tta.GetData();
            if (tdt.Rows.Count > 0)
            {
                pis = float.Parse(tdt.Rows[0]["pis"].ToString());
                cofins = float.Parse(tdt.Rows[0]["cofins"].ToString());
                iof = float.Parse(tdt.Rows[0]["iof"].ToString());
                iss = float.Parse(tdt.Rows[0]["iss"].ToString());
                cpmf = float.Parse(tdt.Rows[0]["cpmf"].ToString());
                adValore = float.Parse(tdt.Rows[0]["adValore"].ToString());
            }
            double desag;
            double totalAdValore = 0;
            
            ClienteTableAdapter cta = new ClienteTableAdapter();
            RizmarDataSet.ClienteDataTable cdt = new RizmarDataSet.ClienteDataTable();
            double taxaMensal = 0;
            double taxaAdm = 0;
            double duplicata = 0;
            cdt = cta.PesquisaPorID(Convert.ToInt32(parent.textBoxCódigo.Text));
            if (cdt.Rows.Count > 0)
            {
                string STtaxaMensal = Convert.ToString(cdt.Rows[0]["taxa"]).Replace('.', ',');
                string STtaxaADM = Convert.ToString(cdt.Rows[0]["adm"]).Replace('.', ',');
                string STduplicata = Convert.ToString(cdt.Rows[0]["duplicata"]).Replace('.', ',');
                taxaMensal = Convert.ToDouble(STtaxaMensal);
                taxaAdm = Convert.ToDouble(STtaxaADM);
                duplicata = Convert.ToDouble(STduplicata);
            }

            int dia = Convert.ToInt32(diasValorLabel.Text);
            double jurosAdm = 0, jurosDesag = 0, totalAdm = 0;
            jurosAdm = ((taxaAdm * 0.01) / 30);
            jurosDesag = ((taxaMensal * 0.01) / 30);
            totalAdm = double.Parse(valorTextBox.Text.Replace('.', ',')) * (double)Math.Pow((1 + jurosAdm), dia) - double.Parse(valorTextBox.Text.Replace('.', ','));
            desag = double.Parse(valorTextBox.Text.Replace('.', ',')) * (double)Math.Pow((1 + jurosDesag), dia) - double.Parse(valorTextBox.Text.Replace('.', ','));
            settaxaAdm(Convert.ToDecimal(totalAdm));
            totalAdValore = adValore * (taxaAdm * desag);
            if (parent.servicoRadioButton.Checked == false)
            {
                setPis(Convert.ToDecimal((pis/100)*desag));
                setCofins(Convert.ToDecimal((cofins/100)*desag));
                setIss(Convert.ToDecimal((iss/100)*taxaAdm));
                setIof(Convert.ToDecimal((iof/100)*float.Parse(diasValorLabel.Text)));
                setCpmf(Convert.ToDecimal((cpmf / 100) * float.Parse(liquidoValorLabel.Text)));

                desag = desag - (desag + totalAdValore) * ((pis + cofins) / 100) - float.Parse(diasValorLabel.Text) * (iof / 100) - (iss / 100) * totalAdValore - (cpmf / 100) * float.Parse(liquidoValorLabel.Text);
            }

            desagioValorLabel.Text = Convert.ToString(decimal.Round(Convert.ToDecimal(desag), 2));
        }

        private void duplicataRadioButton_Click(object sender, EventArgs e)
        {
            if (duplicataRadioButton.Checked)
            {
                bancoTextBox.ReadOnly = false;
                duplicataRadioButton.Checked = false;
                chequeRadioButton.Checked = true;
            }
            else 
            {
                bancoTextBox.ReadOnly = true;
                duplicataRadioButton.Checked = true;
                chequeRadioButton.Checked = false;
            }
        }

        private void chequeRadioButton_Click(object sender, EventArgs e)
        {
            if (duplicataRadioButton.Checked)
            {
                bancoTextBox.ReadOnly = false;
                duplicataRadioButton.Checked = false;
                chequeRadioButton.Checked = true;
            }
            else
            {
                bancoTextBox.ReadOnly = true;
                duplicataRadioButton.Checked = true;
                chequeRadioButton.Checked = false;
            }
        }

        private void chequeRadioButton_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
        }

        private void duplicataRadioButton_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
        }

        internal void setDividaSacadoLabel(int id_sacado) 
        {
            TituloTableAdapter tta = new TituloTableAdapter();
            RizmarDataSet.TituloDataTable tdt1 = new RizmarDataSet.TituloDataTable();
            decimal? soma = 0;
            soma = Convert.ToDecimal(tta.SomaTituloSacado(id_sacado));
            dividaSacadoLabel.Text = Convert.ToString(soma);
        }

        private void dataBaseDateTimePicker_Enter(object sender, EventArgs e)
        {
            dataBaseDateTimePicker.Select();
            dataBaseDateTimePicker.Focus();
            n_digitos = 0;
        }

        private void vencimentoDateTimePicker_Enter(object sender, EventArgs e)
        {
            vencimentoDateTimePicker.Select();
            vencimentoDateTimePicker.Focus();
            n_digitos = 0;
        }
    }
}
